package com.ruoyi.livedemo.service;

import com.ruoyi.livedemo.dto.AnalyticsOverview;
import com.ruoyi.livedemo.dto.AnalyticsOverview.GoalSummary;
import com.ruoyi.livedemo.dto.AnalyticsOverview.InteractionItem;
import com.ruoyi.livedemo.dto.AnalyticsOverview.MoodSlice;
import com.ruoyi.livedemo.dto.AnalyticsOverview.MoodSummary;
import com.ruoyi.livedemo.dto.DiaryMoodCount;
import com.ruoyi.livedemo.entity.GoalItem;
import com.ruoyi.livedemo.mapper.AlbumMediaMapper;
import com.ruoyi.livedemo.mapper.DiaryEntryMapper;
import com.ruoyi.livedemo.mapper.GoalItemMapper;
import com.ruoyi.livedemo.mapper.LifeRecordMapper;
import com.ruoyi.livedemo.mapper.ReminderMapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 甜蜜统计图数据聚合。
 */
@Service
@RequiredArgsConstructor
public class AnalyticsService {

    private static final Map<String, String> MOOD_LABELS;

    static {
        Map<String, String> moodMap = new HashMap<>();
        moodMap.put("快乐", "快乐");
        moodMap.put("幸福", "幸福");
        moodMap.put("平静", "平静");
        moodMap.put("感动", "感动");
        moodMap.put("甜蜜", "甜蜜");
        moodMap.put("思念", "思念");
        moodMap.put("期待", "期待");
        MOOD_LABELS = Collections.unmodifiableMap(moodMap);
    }

    private final GoalItemMapper goalItemMapper;
    private final DiaryEntryMapper diaryEntryMapper;
    private final LifeRecordMapper lifeRecordMapper;
    private final ReminderMapper reminderMapper;
    private final AlbumMediaMapper albumMediaMapper;

    public AnalyticsOverview buildOverview(Long userId) {
        List<GoalItem> goals = goalItemMapper.findByUser(userId);
        if (goals == null) {
            goals = Collections.emptyList();
        }
        GoalSummary goalSummary = buildGoalSummary(goals);

        List<DiaryMoodCount> moodCounts = diaryEntryMapper.countMoodByUser(userId);
        MoodSummary moodSummary = buildMoodSummary(moodCounts);

        int diaryCount = (int) diaryEntryMapper.countByUser(userId);
        int lifeCount = (int) lifeRecordMapper.countByUser(userId);
        int reminderCount = (int) reminderMapper.countByUser(userId);
        int albumCount = (int) albumMediaMapper.countByUser(userId);

        List<InteractionItem> interactions = Arrays.asList(
                InteractionItem.builder().label("甜蜜日志").count(diaryCount).build(),
                InteractionItem.builder().label("生活瞬间").count(lifeCount).build(),
                InteractionItem.builder().label("温暖提醒").count(reminderCount).build(),
                InteractionItem.builder().label("爱的相册").count(albumCount).build()
        );

        List<String> suggestions = buildSuggestions(goalSummary, moodSummary, diaryCount, reminderCount, lifeCount);

        return AnalyticsOverview.builder()
                .goalSummary(goalSummary)
                .moodSummary(moodSummary)
                .interactions(interactions)
                .suggestions(suggestions)
                .build();
    }

    private GoalSummary buildGoalSummary(List<GoalItem> goals) {
        int total = goals.size();
        int completed = 0;
        int inProgress = 0;
        int pending = 0;
        int archived = 0;
        for (GoalItem goal : goals) {
            String status = goal.getStatus();
            if (status != null) {
                status = status.trim().toUpperCase(Locale.ROOT);
            }
            Integer progress = goal.getProgressRatio();
            boolean isCompleted = (status != null && (status.equals("COMPLETED") || status.equals("DONE")))
                    || (progress != null && progress >= 100);
            if (isCompleted) {
                completed++;
                continue;
            }
            if ("IN_PROGRESS".equals(status)) {
                inProgress++;
            } else if ("ARCHIVED".equals(status)) {
                archived++;
            } else {
                pending++;
            }
        }
        int completionRate = total == 0 ? 0 : (int) Math.round(completed * 100.0 / total);
        return GoalSummary.builder()
                .total(total)
                .completed(completed)
                .inProgress(inProgress)
                .pending(pending)
                .archived(archived)
                .completionRate(completionRate)
                .build();
    }

    private MoodSummary buildMoodSummary(List<DiaryMoodCount> moodCounts) {
        if (moodCounts == null || moodCounts.isEmpty()) {
            return MoodSummary.builder()
                    .totalEntries(0)
                    .dominantMood("暂无记录")
                    .dominantPercentage(0)
                    .breakdown(Collections.emptyList())
                    .build();
        }

        long total = moodCounts.stream().mapToLong(DiaryMoodCount::getTotal).sum();
        Comparator<DiaryMoodCount> comparator = Comparator
                .comparingLong(DiaryMoodCount::getTotal).reversed()
                .thenComparing(DiaryMoodCount::getMood, Comparator.nullsLast(String::compareTo));
        DiaryMoodCount dominant = moodCounts.stream().filter(item -> item != null).max(comparator).orElse(moodCounts.get(0));
        int dominantPercent = total == 0 ? 0 : (int) Math.round(dominant.getTotal() * 100.0 / total);

        List<MoodSlice> slices = moodCounts.stream()
                .filter(item -> item != null)
                .sorted(comparator)
                .map(row -> MoodSlice.builder()
                        .label(resolveMoodLabel(row.getMood()))
                        .count(row.getTotal())
                        .build())
                .collect(Collectors.toList());

        return MoodSummary.builder()
                .totalEntries((int) total)
                .dominantMood(resolveMoodLabel(dominant.getMood()))
                .dominantPercentage(dominantPercent)
                .breakdown(slices)
                .build();
    }

    private List<String> buildSuggestions(GoalSummary goalSummary,
                                          MoodSummary moodSummary,
                                          int diaryCount,
                                          int reminderCount,
                                          int lifeCount) {
        List<String> tips = new ArrayList<>();
        if (goalSummary.getCompletionRate() < 60 && goalSummary.getTotal() > 0) {
            tips.add("挑选一个小目标，与爱人一起完成收获满满成就感。");
        }
        if (diaryCount < 5) {
            tips.add("多写写甜蜜日志，留下彼此的心情与故事。");
        }
        if (reminderCount == 0) {
            tips.add("设置一条温暖提醒，别错过值得期待的小计划。");
        }
        if (lifeCount < diaryCount) {
            tips.add("挑几张照片充实生活瞬间，相册会更有温度。");
        }
        if (tips.isEmpty()) {
            tips.add(String.format("保持现在的节奏，继续让“%s”陪伴你们的每一天～", moodSummary.getDominantMood()));
        }
        return tips;
    }

    private String resolveMoodLabel(String rawMood) {
        if (!StringUtils.hasText(rawMood)) {
            return "未填写";
        }
        String trimmed = rawMood.trim();
        return MOOD_LABELS.getOrDefault(trimmed, trimmed);
    }
}
